package com.benmei.weike.service;

import com.benmei.weike.common.Constants;
import com.benmei.weike.dao.CompositeCourseDao;
import com.benmei.weike.dao.WeikeDao;
import com.benmei.weike.dao.WeikeStudentBuyDao;
import com.benmei.weike.dao.WeikeSubscriptionDao;
import com.benmei.weike.dto.PageResponse;
import com.benmei.weike.dto.StudentFindAllCoursePageRequest;
import com.benmei.weike.dto.WeikeDto;
import com.benmei.weike.entity.CompositeCourse;
import com.benmei.weike.entity.WeikeStudentBuy;
import com.benmei.weike.entity.WeikeSubscription;
import com.benmei.weike.entity.WeikeTodayBoutique;
import com.benmei.weike.web.WeikeTeacherController;
import com.nativetalk.bean.live.LiveCourse;
import com.nativetalk.bean.teacher.TeacherLabel;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class CompositeCourseService {

    public static final Logger logger = LoggerFactory.getLogger(WeikeTeacherController.class);

    @Resource
    private CompositeCourseDao compositeCourseDao;

    @Resource
    private WeikeDao weikeDao;

    @Resource
    private WeikeStudentBuyDao weikeStudentBuyDao;

    @Resource
    private WeikeSubscriptionDao weikeSubscriptionDao;

    public int insert(CompositeCourse pojo) {
        return compositeCourseDao.insert(pojo);
    }

    public int insertSelective(CompositeCourse pojo) {
        return compositeCourseDao.insertSelective(pojo);
    }

    public int insertList(List<CompositeCourse> pojos) {
        return compositeCourseDao.insertList(pojos);
    }

    public int update(CompositeCourse pojo) {
        return compositeCourseDao.update(pojo);
    }


    /**
     * 今日精选 包括微课和直播课,只查询3条数据
     *
     * @return
     */
    public List<CompositeCourse> studentFindAllCourseForTodayBoutique() {
        //查询列表
        List<CompositeCourse> compositeCourseList = compositeCourseDao.studentFindAllCourseForTodayBoutique();

        //查询并设置老师的标签
        processTeacherLabels(compositeCourseList);

        //组装分表的数据
        assembleDatas(compositeCourseList);

        return compositeCourseList;
    }


    /**
     * 今日精选-全部 包括微课和直播课
     *
     * @return
     */
    public List<CompositeCourse> studentFindAllCourseForTodayBoutiqueAll(Integer memb_id) {
        //查询列表
        List<CompositeCourse> compositeCourseList = compositeCourseDao.studentFindAllCourseForTodayBoutiqueAll();

        List<WeikeStudentBuy> weikeStudentBuyList = new ArrayList<>();

        if(memb_id != 0 && memb_id != null){
            WeikeSubscription weikeSubscription = weikeSubscriptionDao.findValidSubscribedByMembId(memb_id);
            for(CompositeCourse compositeCourse : compositeCourseList){
                WeikeStudentBuy weikeStudentBuy = new WeikeStudentBuy();
                weikeStudentBuy.setWeike_id(Long.valueOf(compositeCourse.getRef_id()));
                weikeStudentBuy.setMemb_id(memb_id);
                weikeStudentBuyList = weikeStudentBuyDao.find(weikeStudentBuy);
                if(weikeSubscription != null){
                    compositeCourse.setIs_lock(0);
                }
                if(weikeStudentBuyList.size() > 0){
                    compositeCourse.setIs_lock(0);
                }
            }
        }

        //查询并设置老师的标签
        processTeacherLabels(compositeCourseList);

        //组装分表的数据
        assembleDatas(compositeCourseList);

        return compositeCourseList;
    }

    /**
     * 查询并设置老师的标签
     *
     * @param compositeCourseList
     */
    private void processTeacherLabels(List<CompositeCourse> compositeCourseList) {
        List<Integer> teaIds = new ArrayList<>();
        if (compositeCourseList != null && compositeCourseList.size() > 0) {

            for (CompositeCourse cc : compositeCourseList) {
                teaIds.add(cc.getTea_id());
            }
            logger.info("查询并设置老师的标签");
            List<TeacherLabel> teaLabels = compositeCourseDao.getTeachersLabels(teaIds);

            if (teaLabels != null) {
                for (CompositeCourse cc : compositeCourseList) {
                    for (TeacherLabel label : teaLabels) {
                        if (label.getTea_id().intValue() == cc.getTea_id().intValue()) {
                            cc.getTeacher_tags().add(label.getLab_cn_name());
                        }
                    }
                }
            } else {
                logger.info("teaLabels is null,不设置老师标签,teaIds:" + teaIds);
            }
        }
    }

    /**
     * 发现 --> 所有课程
     *
     * @param req
     * @return
     */
    public PageResponse studentFindAllCourse(StudentFindAllCoursePageRequest req) {
        PageResponse pageResponse = new PageResponse(req.getPageSize(), req.getCurrentPage());
        RowBounds rowBounds = new RowBounds(pageResponse.getOffset().intValue(), pageResponse.getPageSize().intValue());

        Integer categor_id = null;
        if (req.getCategory_id() != null && req.getCategory_id() != 0) {
            categor_id = req.getCategory_id();
        }

        //--------------使用union all查询方案，排序规则：1 正在直播的最优先，2 按照时间倒序：直播按照预计开始时间，微课按照最后更新时间排序
        //查询总数
        Long total = compositeCourseDao.studentFindAllCourseCountForUnionAll(categor_id);
//        //查询列表
        List<CompositeCourse> compositeCourseList = compositeCourseDao.studentFindAllCourseForUnionAll(categor_id, rowBounds);


        //组装分表的数据
        assembleDatas(compositeCourseList);

        pageResponse.setTotal(total);
        pageResponse.setData(compositeCourseList);

        return pageResponse;
    }

    /**
     * 发现 --> 所有课程(top10)
     *
     * @return
     */
    public List<CompositeCourse> studentFindAllCourseTop10() {
       StudentFindAllCoursePageRequest req = new StudentFindAllCoursePageRequest();
        req.setCategory_id(null);
        req.setCurrentPage(1L);
        req.setPageSize(10L);
        //查询列表
        PageResponse response = this.studentFindAllCourse(req);
        List<CompositeCourse> compositeCourseList = response.getData();

        //组装分表的数据
        assembleDatas(compositeCourseList);

        return compositeCourseList;
    }

    /**
     * 组装数据：CompositeCourse中的数据来自两张表，weike和live_course，因此根据其类型查询不同的表
     *
     * @param compositeCourseList
     */
    private void assembleDatas(List<CompositeCourse> compositeCourseList) {

        List<Integer> weikeIds = new ArrayList<>();//微课ID列表
        List<Integer> liveCourseIds = new ArrayList<>();//公开课ID列表
        for (CompositeCourse cc : compositeCourseList) {
            if (Constants.CourseType.weike.equals(cc.getCourse_type())) {
                weikeIds.add(cc.getRef_id());
            } else {
                liveCourseIds.add(cc.getRef_id());
            }
        }


        //查询微课
        if (weikeIds.size() > 0) {
            logger.info("查询微课");
            List<WeikeDto> weikes = weikeDao.getByIds(weikeIds);

            if (weikes != null && weikes.size() > 0) {
                for (CompositeCourse cc : compositeCourseList) {
                    if (Constants.CourseType.weike.equals(cc.getCourse_type())) {
                        for (WeikeDto weikeDto : weikes) {
                            if (weikeDto.getId().equals(cc.getRef_id())) {
                                cc.setCourse_cover_url(weikeDto.getCover_url_student());
                                cc.setPrice(weikeDto.getStudent_price());
                                cc.setTitle(weikeDto.getTitle_student());
                                cc.setUpdate_lesson_count(weikeDto.getUpdate_lesson_count());
                                cc.setViewer_count(weikeDto.getViewer_count());
                                cc.setCategory_id(weikeDto.getCategory_id());
                                cc.setCategory_name(weikeDto.getCategory_name());
                                cc.setTeacher_name(weikeDto.getTeacher_name());
                                cc.setTeacher_avatar_url(weikeDto.getTeacher_avatar_url());
                                cc.setTeacher_valid(weikeDto.getTeacher_valid());
                                cc.setWeike_score(weikeDto.getScore());
                            }
                        }
                    }
                }
            }

        }

    }

    private List<TeacherLabel> getTeachersLabels(List<Integer> teaIds) {
        return compositeCourseDao.getTeachersLabels(teaIds);
    }

}
